const express = require('express');
const router = express.Router();
let tools = require('../../../utils/multer');
let md5 = require("../../../utils/md5");
const qx = require("../../../utils/qx")
const url = require("url")
const {
    mysql,
    localStorage
} = require("../../../utils/require");

//查询所有用户及分页
router.post('/', async(req, res) => {
        let http = `${req.protocol}://${req.headers.host}`;
        const body = req.body;
        let pageSize = body.limit || 10; //分页参数
        let currenPage = body.currenPage || 1; //当前页码
        let startRow = (currenPage - 1) * pageSize;
        let sql = "select username,status,nickname,DATE_FORMAT(datetime,'%Y-%m-%d %H:%i:%s') as datetime,concat( ?,avatar) as avatar from `user`  ORDER BY datetime desc  limit ?, ?";
        mysql.query(sql, [http, startRow, pageSize], (err, data) => {
            if (err) {
                throw err;
            }
            let count = "select count(*)  as count from `user` ";
            mysql.query(count, (err, count) => {
                if (err) {
                    throw err;
                }
                res.send({ count: count[0].count, data, qx: localStorage.getItem("qx") })

            })

        })



    })
    //改变用户状态
router.post('/status', async(req, res) => {
    const { username } = req.body;
    let Permission = await qx.pbulic_qx(req.session.users.id);
    if (Permission.indexOf(1) > -1 || Permission.indexOf(2) > -1 || Permission.indexOf(4) > -1) {
        let sql = "update `user` set status= CASE WHEN status=0 then 1 else 0 END  where  username =  ?";
        mysql.query(sql, username, (err, data) => {
            if (err) {
                throw err;
            }
            mysql.query("select  status from `user` where username =  ?", username, (err, doc) => {
                if (doc[0].status == 0) {
                    res.send({
                        messages: "账号已关闭"
                    })
                } else {
                    res.send({
                        messages: "账号已开启"
                    })
                }

            })

        })
    } else {
        res.send({
            code: 400,
            messages: "没有权限"
        })
    }


})

//删除用户
router.post('/delete', async(req, res) => {
        const { username } = req.body;
        let Permission = await qx.pbulic_qx(req.session.users.id);
        if (Permission.indexOf(1) > -1 || Permission.indexOf(2) > -1 || Permission.indexOf(5) > -1) {
            mysql.query("select avatar  from `user`  where  username =  ?", username, async(err, doc) => {
                await tools.delfolder(doc[0].avatar)
                let sql = "delete from `user`  where  username =  ?";
                mysql.query(sql, username, (err, data) => {
                    if (err) {
                        throw err;
                    }
                    res.send({
                        messages: "账号已删除"
                    })
                })
            })
        } else {
            res.send({
                code: 400,
                messages: "没有权限"
            })
        }


    })
    //增加用户
router.post('/adduser', async(req, res) => {
        const { username, password, nickname } = req.body;
        let Permission = await qx.pbulic_qx(req.session.users.id);
        if (Permission.indexOf(1) > -1 || Permission.indexOf(2) > -1 || Permission.indexOf(3) > -1) {
            let name = nickname == '' ? '未设置' : nickname;
            mysql.query("select username from `user` where username =? ", username, (err, data) => {
                if (err) {
                    throw err;
                }
                if (data.length == 1) {
                    res.send({
                        messages: "用户已存在"
                    })
                } else {

                    let sql = "insert into `user` (username, password, nickname) values (?,?,?)";
                    let pwd = md5(md5(password).substr(2, 8) + md5(password))
                    mysql.query(sql, [username, pwd, name], (err, doc) => {
                        if (err) {
                            throw err;
                        }
                        res.send({
                            messages: "添加用户成功"
                        })
                    })
                }

            })
        } else {
            res.send({
                code: 400,
                messages: "没有权限"
            })
        }
    })
    //用户模糊查询
router.post('/likeuser', async(req, res) => {
        const { keyword } = req.body;
        let keywords = "%" + keyword + "%";
        let http = `${req.protocol}://${req.headers.host}`;
        let sql = "select username,status,nickname,DATE_FORMAT(datetime,'%Y-%m-%d %H:%i:%s') as datetime,concat( ?,avatar) as avatar from `user` where username like ? or nickname like ? ORDER BY datetime desc";
        await mysql.query(sql, [http, keywords, keywords], (err, doc) => {
            if (err) {
                throw err;
            }
            res.send(doc)
        })

    })
    //重置初始密码为123456
router.post('/setpassword', async(req, res) => {
    const { username } = req.body;
    let Permission = await qx.pbulic_qx(req.session.users.id);
    if (Permission.indexOf(1) > -1 || Permission.indexOf(2) > -1 || Permission.indexOf(4) > -1) {
        let pwd = md5(md5("123456").substr(2, 8) + md5("123456"))
        let sql = "update  `user` SET password =? where  username =  ?";
        mysql.query(sql, [pwd, username], (err, data) => {
            if (err) {
                throw err;
            }
            res.send({
                messages: "密码重置成功"
            })

        })

    } else {
        res.send({
            code: 400,
            messages: "没有权限"
        })
    }


})


//上传头像
let upload = tools.multer().single("avatar");
router.post('/avatarUpload', upload, async(req, res) => {
    const { username } = req.body;
    let Permission = await qx.pbulic_qx(localStorage.getItem('id'));
    if (Permission.indexOf(1) > -1 || Permission.indexOf(2) > -1 || Permission.indexOf(4) > -1) {
        let http = `${req.protocol}://${req.headers.host}`;
        upload(req, res, (err) => {

            if (err) {
                res.send({
                    messages: "上传错误"
                })
                return
            }

            let filePath = req.file.path.substring(6).replace(/\\/g, "/");
            mysql.query("select avatar from `user`  where username= ?", [username], (err, doc) => {
                    tools.delfolder(doc[0].avatar); //

                    let sql = " update  `user` set avatar= ? where username= ?";

                    mysql.query(sql, [filePath, username], (error, data) => {
                        if (error) {
                            throw error;
                        }
                        let sqls = "select username,status,nickname,DATE_FORMAT(datetime,'%Y-%m-%d %H:%i:%s') as datetime,concat( ?,avatar) as avatar from `user`  ";
                        mysql.query(sqls, [http], (err, data) => {
                            if (err) {
                                throw err;
                            }
                            res.send({
                                code: 200,
                                messages: "修改成功",
                                data
                            })

                        })



                    })
                }) //查询end

        })
    } else {
        res.send({
            code: 400,
            messages: "没有权限"
        })
    }



})


module.exports = router